<script language="javascript"> 	
	   curNode = null ;
	   var cellmergestart  , cellmergend;
	   var selNum = 0 ;
	   var selcolinx ;		//当前选中的 列，求和用
	   var curSelCell ;
	//还原包含rowspan/colspan的表格，将多余的td设置为display:none
	   $.fn.RevertTable=function(){ 
            $("tr",this).each(function(trindex,tritem){ 
                $(tritem).find("td").each(function(tdindex,tditem){ 
                    var col=$(tditem).attr("colspan"),
                        row=$(tditem).attr("rowspan"),
                        data_id=$(tditem).attr("data-id"),
                        c = col>1?col:1,
                        r = row>1?row:1,
                        index = $(tditem).index(),
                        curr = $(tditem).parent();
                    var value = $(tditem).text(); 
                    if(data_id != undefined){
                        data_id = " data-id="+data_id;
                    }else{
                        data_id = "";
                    }
                    var newtd = "<td style=\"display:none\""+data_id+">"+value+"</td>";
                    while(r--){
                         c = col>1?col:1;
                         while(--c){
                            curr.find('td').eq(index).after(newtd);
                         }
                         
                         if(r){
                             curr = curr.next();
                             curr.find('td').eq(index).before(newtd);
                         }
                     }
                     //$(tditem).attr("colspan",1); 
                     //$(tditem).attr("rowspan",1); 
                }); 
            }); 
        } 
        //TD重新赋值  
        $.fn.SetNewValueTd=function(text){ 
            var col=this.attr("colspan"),
                row=this.attr("rowspan"),
                c = col>1?col:1,
                r = row>1?row:1,
                index = this.index(),
                curr = this.parent(); 
            while(r--){//如果rowspan大于等于1
                 c = col>1?col:1;
                 while(c--){//如果colspan大于等于1
                    curr.find('td').eq(index+c).text(text);
                 }
                 curr = curr.next();
             }
        } 
         
	    $(function () {
			/**
			* 将选择的 行或列置空
			*/
	        selColDataID = null ;
	        var curr_opt_obj = null;
	        //设置允许对表格指定的元素进行选中的动作
            function setSelectable(currTable){
                currTable.find("tbody").selectable({
                    filter: ".needSelect",
                    start:function(){
                        seletable.find("tr td,tr th").removeClass('ui-selected'); 
                        //showTopHighLight(seletable);
                        curr_opt_obj = currTable;
						cellmergestart = null ;
                    },
					stop:function(){
						if(curNode!=null && curNode.type =="chart"){
							if(curNode.action == 'series_data'){
								BtnAction.chartvaluerange(curNode ,curSelCell.attr('data-title') , curSelCell.attr('data-index') , cellmergestart , cellmergend ,'#cz_<#if reportModel??>${reportModel.id!''}</#if>');
								curNode.name = curSelCell.attr('data-title') ;
								dataModelPropertiesTree.updateNode(curNode);
							}
						}
					},
                    create:function(){
                        var elemself = $(this);
                        var thd = currTable.find("thead");
                        var ths = thd.find("td").filter(":not('.s_blue')");
                        ths.click(function(event) {//列全选
                            curr_opt_obj = currTable;
                            var colnum = $(this).index()+1;
                            seletable.find("tr td,tr th").removeClass('ui-selected'); 
                            var colspan = $(this).attr('colspan')?$(this).attr('colspan'):1;
                            var tridx = $(this).parent().index();    
                            $(this).addClass("ui-selected");                        
                            if(colspan){
                                 while(colspan){
                                     currTable.find("tr:gt("+tridx+")").find("td").filter(":nth-child("+colnum+")").addClass("ui-selected");
                                     colnum++;
                                     colspan--;
                                 }
                            }
							selColDataID = $(this) ;
							//alert($(this).attr("data-id"));
							/**
							** 回调操作，如果当前窗口的 公式计算 窗口存在，则将此指标加入到 公式计算中
							*/
							if($('#expressmeasure').length > 0){
								BtnAction.operators('#expressmeasure' , decodeURIComponent($(this).attr('data-title')));
							}
							if(curNode!=null && ($(this).attr('data-flag') == 'measure' || $(this).attr('data-flag') == 'newcol') && curNode.type =="chart"){
								var name = decodeURIComponent($(this).attr('data-title')) ;
								if(curNode.action == 'serise'){
									BtnAction.setYAxisData(curNode.pkgid , $(this).attr('data-title'), $(this).attr('data-index') ,'#design_table');
								}else if(curNode.action == 'series_data'){
									BtnAction.chartvalue(curNode , $(this).attr('data-title'), $(this).attr('data-index') ,'#cz_<#if reportModel??>${reportModel.id!''}<#else></#if>');
									curNode.name = name ;
									dataModelPropertiesTree.updateNode(curNode);
								}else if(curNode.action == 'yaxis'){
									//BtnAction.chartvalue(curNode , $(this).attr('data-title') ,'#chart_<#if reportModel??>${reportModel.id!''}</#if>');
								}
								
							}
							if(curNode!=null && $(this).attr('data-flag') == 'dim' && curNode.type =="chart"){
								var name = decodeURIComponent($(this).attr('data-title')) ;
								if(curNode.action == 'xaxis'){
									BtnAction.setXAxisData(curNode.pkgid , $(this).attr('data-title') , '#chart_<#if reportModel??>${reportModel.id!''}</#if>');
									curNode.name = "X轴数据："+name ;

									dataModelPropertiesTree.updateNode(curNode);
								}
								
							}

							if(BtnAction.selRowData == "event"){
								if($(this).attr('data-flag') == 'dim'){
									inserCurDimTitleToEvent($(this) , '${report.name!""}' , '<#if reportModel??>${reportModel.title!index!"0"}</#if>') ;
								}else{
									inserCurMeasureTableDataToEvent($(this) , '${report.name!""}' , '<#if reportModel??>${reportModel.title!index!"0"}</#if>') ;
								}
							}
							event.stopPropagation();//点击Button阻止事件冒泡到document
                        });  
                        var trs = currTable.find("tbody").find("tr td").filter('.blue_k');
                        trs.click(function() { //行全选
                            //showTopHighLight(this);
                            curr_opt_obj = currTable;
                            seletable.find("tr td,tr th").removeClass('ui-selected');
                            lastSelect = $(this).parent().find('td');
                            var rowspan = $(this).attr('rowspan')?$(this).attr('rowspan'):1;
                            if(rowspan){
                                 var currTarget = $(this).parent();
                                 while(rowspan){
                                     currTarget.find('td').addClass("ui-selected");
                                     currTarget = currTarget.next();
                                     rowspan--;
                                 }
                            }								
							selColDataID = $(this) ;

							if(BtnAction.selRowData == "event"){
								inserCurDimTableDataToEvent($(this) , '${report.name!""}' , '<#if reportModel??>${reportModel.title!index!"0"}</#if>') ;
							}
                        });   
                        //解决添加select后click事件失效的问题
                        elemself.on("mouseover",".blue_k",function(){
                            currTable.find("tbody").selectable("disable");
                        }).on("mouseout",".blue_k",function(){
                            currTable.find("tbody").selectable("enable");
                        }); 
                        //  console.log(ths)
                    },
					selected: function( event, ui ) {
						var selected = $(ui.selected) ; 
						if(selected.find("a").length>0){//触发该单位里的超链接事件
							var $cr=selected.find("a");
							var cr=$cr[0];
							cr.click();
						}
						var row =selected.parents('tr').index(),
							col = selected.attr("data-index");
						if(cellmergestart == null){
							 cellmergestart = col+":"+row ;
						}
						cellmergend = col+":"+row ;
						curSelCell = selected;
						selNum++;
					}
                }); 				
				if(selColDataID!=""){
					$('#'+$(selColDataID).attr('data-rowno')).click();
				}
				$("#design_table").unbind("click");
				$("#design_table").bind("click", function(){
					$(".selectableTable").find("tr td,tr th").removeClass('ui-selected'); 
					selColDataID = "" ;
				});
            }
	        //设置表格列拖动
            function setSortable(currTable){
                currTable.find("thead tr.sortableTr").sortable({
                    helper: "clone",
                    items:"td:not(.s_blue)",
                    start:function(event,ui) {
                        startIndex = ui.item.index();
                        seletable.find("tr td,tr th").removeClass('ui-selected'); 
                        ui.helper.css({
                            "vertical-align":"top",
                            "height": ui.item.height()
                        })
                    },
                    stop:function(event,ui){
                        var sortableIndex = ui.item.index();
                        if(sortableIndex != startIndex){
                            var oldValue = [];
                            var tr_arr = currTable.find("tbody").find("tr");
                            var tr_len = tr_arr.length;
                            for(var k=0; k<tr_len; k++) {//获取起始列的值
                                tditem = tr_arr.eq(k).find("td").eq(startIndex);
                                oldValue.push(tditem.text());
                            }
                            var i = startIndex;
                            if(i < sortableIndex){//后移
                                while(i < sortableIndex){
                                    for(var k=0; k<tr_len; k++) {
                                        tditem = tr_arr.eq(k).find("td").eq(i);
                                        if(tditem.hasClass('needSelect')){
                                            tditem.SetNewValueTd(tr_arr.eq(k).find("td").eq(i+1).text());
                                        }  
                                    }
                                    i++;                             
                                }
                            }else{//前移
                                while(i > sortableIndex){
                                    for(var k=0; k<tr_len; k++) {
                                        tditem = tr_arr.eq(k).find("td").eq(i);
                                        if(tditem.hasClass('needSelect')){
                                            tditem.SetNewValueTd(tr_arr.eq(k).find("td").eq(i-1).text());
                                        }  
                                    }
                                    i--;                             
                                }
                            }
                            for(var k=0; k<tr_len; k++) {//将起始列的值赋值给目标列
                                tditem = tr_arr.eq(k).find("td").eq(sortableIndex);
                                if(tditem.hasClass('needSelect')){
                                    tditem.SetNewValueTd(oldValue[k]);
                                }
                            }
                        }
                    },
                    create:function(){
                         
                    }  
                }).disableSelection();
            }
	        var seletable = $(".selectableTable");
            var startIndex;
            seletable.find("td").filter(":not('.blue_k')").addClass("needSelect");
            seletable.each(function() {
                var currTable = $(this);
                currTable.RevertTable();
                setSelectable(currTable);
				setSortable(currTable);
            });
			<#if exchange??>
				ReportAction.tipOperInfo("${exchange!''}");
			</#if>

	    });
	    
	    function showHelpMsg(obj){
	    	var str = $(obj).parent().find("textarea").html();
			art.alert("<div style='height: 100px;width:500px; overflow-y: scroll;'>"+$(obj).parent().find("textarea").html()+"</div>");
	    }
	    function do_sort(obj,sortType){
	    	loadURL("/${orgi}/design/query/${report.id!''}/<#if reportModel??>${reportModel.id!''}</#if>/queryFilter.html?sortType="+sortType+"&sortName="+encodeURIComponent(obj) , "#design_table");
	    }
</script>
<div class="newDom ui-sortable noborder" style="overflow: auto;height:100%;">	
    <div style="font-weight:  " class="ppdiv"></div>
	<#if reportModel??>
	<table class="selectableTable <#if reportModel?? && reportModel.viewtype == 'view'>cz_${reportModel.id}</#if>" data-id="${reportModel.id!''}_${reportModel.viewtype}">
		<thead>
			<#if reportModel?? && reportModel.reportData?? && reportModel.reportData.col?? && reportModel.reportData.col.title??>
				<#list reportModel.reportData.col.title as tlist>
					<tr>
						<#if reportModel.reportData.col.title?size gt 1 && tlist_index == 0 && reportModel.reportData.row.title?size gt 0>
						<td colspan="${reportModel.reportData.row.title?size}" rowspan="${reportModel.reportData.col.title?size-1}" class="s_blue"></td>	
						</#if>
						<#if (tlist_index+1) == reportModel.reportData.col.title?size && reportModel.reportData.row?? && reportModel.reportData.row.firstTitle??>
						<#list reportModel.reportData.row.firstTitle as first>
						<td align="center" data-title="${first.name?url}" data-flag="dim">
							${first.rename!first.name!''}
							<#if first.description??><img style="cursor: pointer;" onclick="showHelpMsg(this)" title="维度描述" width="10" height="10" src="/assets/images/help.png"></#if>
							<textarea style="display: none">${first.description!''}</textarea>
						</td>
						</#list>
						</#if>
						<#if tlist??>
						<#list tlist as tl>
						<td data-index="${tl_index}"   id="cz_tl_${tl_index}" data-rowno="cz_tl_${tl_index}" data-title="<#if reportModel.reportData.col.firstTitle?? && reportModel.reportData.col.firstTitle[tlist_index]?? && reportModel.reportData.col.firstTitle[tlist_index].name != '指标'>${reportModel.reportData.col.firstTitle[tlist_index].name?url}<#else>${tl.name?url}</#if>" <#if tl.leveltype?? && tl.leveltype == 'newcol'>data-id="${tl.nameValue!''}"</#if> data-flag="<#if tl.leveltype?? && tl.leveltype == 'newcol'>newcol<#elseif tlist_index == (reportModel.reportData.col.title?size-1) && reportModel.exchangerw == false>measure<#else>dim</#if>" <#if  tl.leveltype?? && tl.leveltype == "newcol">rowspan="${reportModel.reportData.col.title?size}"</#if> colspan="${tl.colspan}" data-pos='${tl.dataid}'>
							${tl.rename!tl.formatName!''}
							<#if tl.description??><img style="cursor: pointer;" onclick="showHelpMsg(this)" title="指标描述" width="10" height="10" src="/assets/images/help.png"></#if>
							<#if tl.leveltype??&&tl.leveltype != 'newcol'&&cube?? && cube.dstype=='table'><img style="cursor: pointer;" onclick="do_sort('${tl.formatName!''}',<#if reportModel.sortType??&&reportModel.sortType=='asc'>'desc'<#else>'asc'</#if>)" title="排序" width="10" height="10" <#if reportModel.sortName??&& (reportModel.sortName==tl.rename!tl.formatName) &&(reportModel.sortType=='asc')>src="/assets/images/arrow-up.png"<#elseif reportModel.sortName??&& (reportModel.sortName==tl.rename!tl.formatName) &&(reportModel.sortType=='desc')>src="/assets/images/arrow-down.png"<#else>src="/assets/images/report-view-sort.png"</#if>></#if>
							<textarea style="display: none">${tl.description!''}</textarea>
						</td>
						</#list>
						</#if>
					</tr>
				</#list>
			</#if>
		</thead>
		<tbody>
			<#if reportModel.reportData?? && reportModel.reportData.data??>
				<#list reportModel.reportData.data as values>
				<tr class="rowcell">	  
					<#if reportModel.reportData.row?? && reportModel.reportData.row.title?? && reportModel.reportData.row.title?size gt 0>
						<#list reportModel.reportData.row.title as tl>
							<#assign rows = 0 >
							<#list tl as title>
								<#if title??>
									<#if rows == values_index && title.name != "TOTAL_TEMP">
										<#if title.leveltype != "newrow_extend_sum">
										<td nowrap="nowrap"  class="blue_k <#if title.total == true>total</#if>" data-index="${title_index}"  data-title="<#if tl_index == reportModel.reportData.row.title?size-1 && reportModel.exchangerw == true>${title.name?url}<#else>${reportModel.reportData.row.firstTitle[tl_index].name?url}</#if>" <#if title.leveltype?? && title.leveltype == 'newrow'>data-id="${title.nameValue!''}"</#if> data-flag="<#if title.leveltype?? && title.leveltype == 'newrow'>newrow<#elseif tl_index == reportModel.reportData.row.title?size-1 && reportModel.exchangerw == true>measure<#else>dim</#if>" rowspan="${title.rowspan!'0'}" <#if title.colspan gt 1>colspan="${title.colspan}"</#if> data-pos="${title.dataid!''}"><#if title.formatName??&&title.formatName?trim?length==0>&nbsp;</#if><#noescape>${title.formatName!''}</#noescape></td>
										</#if>
										<#if title.valueData??>
											<#list title.valueData as value>
												<#if value.merge==false>
												<td rowspan="${value.rowspan}" colspan="${value.colspan}" data-title="${value.name!''?url}"  data-index="${value_index}" data-flag="mea"  class="<#if title.total == true>total</#if> ui-state-default measure ${value.vtclass!''} <#if (values_index+1) % 2 == 1>cz_${reportModel.id}_odd cz_${value.dataid}_odd<#else>cz_${reportModel.id}_even cz_${value.dataid}_even</#if>  cz_${reportModel.id} cz_${value.dataid!''} " nowrap="nowrap" <#if value.cellmergeid??>data-cellmerge="${value.cellmergeid}"</#if>><#noescape>${value.valueStyle!value.foramatValue!''}</#noescape></td>
												</#if>
											</#list>
										</#if>
									</#if>
									<#assign rows = rows + title.rowspan>
								</#if>
							</#list>
						</#list>
					<#else>
						<#list values as value>
							<td data-index="${value_index}" data-flag="mea" data-title="${value.name!''?url}"   class="ui-state-default  ${value.vtclass!''}  <#if (values_index+1) % 2 == 1>cz_${reportModel.id}_odd cz_${value.dataid}_odd<#else>cz_${reportModel.id}_even cz_${value.dataid}_even</#if>  cz_${reportModel.id} cz_${value.dataid!''}" nowrap="nowrap" align="right"><#noescape>${value.valueStyle!value.foramatValue!''}</#noescape></td>
						</#list>
					</#if>
				</tr>
				</#list>
			</#if>
		</tbody>
	</table>
	</#if>
</div>
